#include "system_manager.h"
#include "logger.h"
#include <stdlib.h>
#include <string.h>

// 新增数据库更新事件处理
void system_manager_handle_db_update(system_manager_t *manager, event_t *event) {
    char *key = (char *)event->data;
    LOG_INFO("Database updated: %s", key);

    // 这里可以实现数据库更新后的业务逻辑
    // 例如：备份、同步、通知等
}

int system_manager_init(system_manager_t *manager) {
    if (!manager) {
        return ERROR_INVALID_PARAM;
    }

    memset(manager, 0, sizeof(system_manager_t));

    // 初始化数据库管理器
    manager->db_mgr = malloc(sizeof(db_manager_t));
    if (db_manager_init(manager->db_mgr, "system.db") != SUCCESS) {
        LOG_ERROR("Failed to init database manager");
        goto error;
    }

    // 初始化事件循环
    manager->event_loop = malloc(sizeof(event_loop_t));
    if (event_loop_init(manager->event_loop, "main", MAX_EVENTS) != SUCCESS) {
        LOG_ERROR("Failed to init event loop");
        goto error;
    }

    // 初始化配置管理器（传入数据库管理器）
    manager->config = malloc(sizeof(config_manager_t));
    if (config_manager_init(manager->config, manager->db_mgr, true) != SUCCESS) {
        LOG_ERROR("Failed to init config manager");
        goto error;
    }

    // 初始化数据池（传入数据库管理器）
    manager->data_pool = malloc(sizeof(data_pool_t));
    json_t *pool_config = config_manager_get(manager->config, "data_pool.max_size");
    size_t max_size = json_integer_value(pool_config) ?: 1000;
    if (data_pool_init(manager->data_pool, max_size, manager->event_loop, manager->db_mgr) != SUCCESS) {
        LOG_ERROR("Failed to init data pool");
        goto error;
    }

    // 初始化定时器管理器
    manager->timer = malloc(sizeof(timer_manager_t));
    if (timer_manager_init(manager->timer, manager->event_loop) != SUCCESS) {
        LOG_ERROR("Failed to init timer manager");
        goto error;
    }

    // 注册事件处理器
    event_loop_register_handler(manager->event_loop, EVENT_API_RESPONSE,
                                (event_handler_t)system_manager_handle_api_response);
    event_loop_register_handler(manager->event_loop, EVENT_DATA_UPDATE,
                                (event_handler_t)system_manager_handle_data_update);
    event_loop_register_handler(manager->event_loop, EVENT_TIMER_TRIGGER,
                                (event_handler_t)system_manager_handle_timer_trigger);
    event_loop_register_handler(manager->event_loop, EVENT_DATA_CHECK,
                                (event_handler_t)system_manager_handle_data_check);
    event_loop_register_handler(manager->event_loop, EVENT_DB_UPDATE,
                                (event_handler_t)system_manager_handle_db_update);

    // 记录系统启动状态到数据库
    json_t *status_details = json_object();
    json_object_set_new(status_details, "version", json_string("1.0.0"));
    json_object_set_new(status_details, "start_time", json_integer(time(NULL)));

    db_system_status_set(manager->db_mgr, "system_manager", "running", status_details);
    json_decref(status_details);

    manager->initialized = true;
    return SUCCESS;

error:
    system_manager_cleanup(manager);
    return ERROR_INVALID_PARAM;
}

// 新增数据库备份函数
int system_manager_backup_database(system_manager_t *manager, const char *backup_path) {
    if (!manager || !manager->db_mgr || !backup_path) {
        return ERROR_INVALID_PARAM;
    }

    // 在实际实现中，这里应该使用SQLite的备份API
    // 简化实现：复制数据库文件
    char cmd[1024];
    snprintf(cmd, sizeof(cmd), "cp %s %s", manager->db_mgr->db_path, backup_path);

    int rc = system(cmd);
    if (rc == 0) {
        LOG_INFO("Database backed up to: %s", backup_path);
        return SUCCESS;
    } else {
        LOG_ERROR("Failed to backup database to: %s", backup_path);
        return ERROR_DB_OPERATION;
    }
}

// 新增数据库恢复函数
int system_manager_restore_database(system_manager_t *manager, const char *backup_path) {
    if (!manager || !manager->db_mgr || !backup_path) {
        return ERROR_INVALID_PARAM;
    }

    // 停止系统以确保数据一致性
    system_manager_stop(manager);

    // 在实际实现中，这里应该使用SQLite的恢复API
    // 简化实现：复制备份文件
    char cmd[1024];
    snprintf(cmd, sizeof(cmd), "cp %s %s", backup_path, manager->db_mgr->db_path);

    int rc = system(cmd);
    if (rc == 0) {
        LOG_INFO("Database restored from: %s", backup_path);

        // 重新加载配置和数据
        config_manager_reload(manager->config);
        data_pool_load_from_db(manager->data_pool);

        // 重新启动系统
        return system_manager_start(manager);
    } else {
        LOG_ERROR("Failed to restore database from: %s", backup_path);
        return ERROR_DB_OPERATION;
    }
}

void system_manager_cleanup(system_manager_t *manager) {
    if (!manager) {
        return;
    }

    system_manager_stop(manager);

    // 记录系统停止状态到数据库
    if (manager->db_mgr && manager->db_mgr->initialized) {
        json_t *status_details = json_object();
        json_object_set_new(status_details, "stop_time", json_integer(time(NULL)));
        db_system_status_set(manager->db_mgr, "system_manager", "stopped", status_details);
        json_decref(status_details);
    }

    if (manager->timer) {
        timer_manager_destroy(manager->timer);
        free(manager->timer);
    }

    if (manager->data_pool) {
        data_pool_destroy(manager->data_pool);
        free(manager->data_pool);
    }

    if (manager->config) {
        config_manager_destroy(manager->config);
        free(manager->config);
    }

    if (manager->event_loop) {
        event_loop_cleanup(manager->event_loop);
        free(manager->event_loop);
    }

    if (manager->db_mgr) {
        db_manager_close(manager->db_mgr);
        free(manager->db_mgr);
    }
}

// API任务回调函数
static void api_task_callback(api_response_t *response, void *user_data) {
    system_manager_t *manager = (system_manager_t *)user_data;

    if (response->status_code == 200 && response->response_data) {
        // 处理API响应数据
        LOG_INFO("API call successful, processing response");

        // 这里可以根据配置将数据存储到数据池
        // 简化示例：直接将整个响应存储
        data_pool_put(manager->data_pool, "api.last_response", response->response_data);

        // 发送API响应事件
        event_t *event = event_create(EVENT_API_RESPONSE, response, sizeof(api_response_t), NULL);
        if (event) {
            event_loop_send_event(manager->event_loop, event);
            event_destroy(event);
        }
    } else {
        LOG_ERROR("API call failed: %s", response->error_msg ? response->error_msg : "Unknown error");
    }
}

// 定时器回调 - API调用任务
static void api_timer_callback(void *arg) {
    system_manager_t *manager = (system_manager_t *)arg;
    config_manager_t *config = manager->config;

    // 获取所有API配置
    json_t *apis = config_manager_get(config, "apis");
    if (!apis || !json_is_object(apis)) {
        return;
    }

    const char *api_name;
    json_t *api_config;
    json_object_foreach(apis, api_name, api_config) {
        api_config_t *api = config_get_api_config(config, api_name);
        if (api && api->enabled) {
            // 创建API任务
            api_task_t *task = malloc(sizeof(api_task_t));
            if (task) {
                task->request.name = strdup(api->name);
                task->request.url = strdup(api->url);
                task->request.method = strdup(api->method);
                task->request.headers = json_deep_copy(api->headers);
                task->request.params = json_deep_copy(api->params);
                task->request.body = json_deep_copy(api->body);
                task->request.timeout_ms = api->timeout_ms;

                task->callback = api_task_callback;
                task->user_data = manager;
                task->event_loop = manager->event_loop;

                // 异步执行API调用
                api_client_make_request_async(task);
            }
        }
        config_free_api_config(api);
    }
}

// 定时器回调 - 数据检查任务
static void data_check_timer_callback(void *arg) {
    system_manager_t *manager = (system_manager_t *)arg;
    config_manager_t *config = manager->config;

    // 获取所有监控配置
    json_t *monitors = config_manager_get(config, "monitors");
    if (!monitors || !json_is_object(monitors)) {
        return;
    }

    const char *monitor_name;
    json_t *monitor_config;
    json_object_foreach(monitors, monitor_name, monitor_config) {
        monitor_config_t *monitor = config_get_monitor_config(config, monitor_name);
        if (monitor && monitor->enabled) {
            // 根据模式查找数据
            size_t count;
            data_item_t **items = data_pool_find_by_pattern(manager->data_pool, monitor->key_pattern, &count);

            if (items) {
                for (size_t i = 0; i < count; i++) {
                    // 检查数据值是否符合阈值条件
                    // 这里可以实现具体的阈值检查逻辑
                    LOG_DEBUG("Checking data: %s", items[i]->key);

                    // 发送数据检查事件
                    char *key_copy = strdup(items[i]->key);
                    event_t *event = event_create(EVENT_DATA_CHECK, key_copy, strlen(key_copy) + 1, free);
                    if (event) {
                        event_loop_send_event(manager->event_loop, event);
                        event_destroy(event);
                    }
                }
                data_pool_free_search_result(items);
            }
        }
        config_free_monitor_config(monitor);
    }
}

// 事件处理函数
void system_manager_handle_api_response(system_manager_t *manager, event_t *event) {
    LOG_INFO("Handling API response event");
    // 处理API响应，可以根据需要更新数据池或触发其他操作
}

void system_manager_handle_data_update(system_manager_t *manager, event_t *event) {
    char *key = (char *)event->data;
    LOG_INFO("Data updated: %s", key);

    // 这里可以实现数据更新后的业务逻辑
    // 例如：数据验证、转换、通知等
}

void system_manager_handle_timer_trigger(system_manager_t *manager, event_t *event) {
    LOG_DEBUG("Timer trigger event received");
}

void system_manager_handle_data_check(system_manager_t *manager, event_t *event) {
    char *key = (char *)event->data;
    LOG_INFO("Data check for: %s", key);

    // 这里可以实现具体的数据检查逻辑
    // 例如：阈值检查、状态评估等
}

int system_manager_init(system_manager_t *manager) {
    if (!manager) {
        return ERROR_INVALID_PARAM;
    }

    memset(manager, 0, sizeof(system_manager_t));

    // 初始化事件循环
    manager->event_loop = malloc(sizeof(event_loop_t));
    if (event_loop_init(manager->event_loop, "main", MAX_EVENTS) != SUCCESS) {
        LOG_ERROR("Failed to init event loop");
        goto error;
    }

    // 初始化配置管理器
    manager->config = malloc(sizeof(config_manager_t));
    if (config_manager_init(manager->config, "config/system_config.json", true) != SUCCESS) {
        LOG_ERROR("Failed to init config manager");
        goto error;
    }

    // 初始化数据池
    manager->data_pool = malloc(sizeof(data_pool_t));
    json_t *pool_config = config_manager_get(manager->config, "data_pool.max_size");
    size_t max_size = json_integer_value(pool_config) ?: 1000;
    if (data_pool_init(manager->data_pool, max_size, manager->event_loop) != SUCCESS) {
        LOG_ERROR("Failed to init data pool");
        goto error;
    }

    // 初始化定时器管理器
    manager->timer = malloc(sizeof(timer_manager_t));
    if (timer_manager_init(manager->timer, manager->event_loop) != SUCCESS) {
        LOG_ERROR("Failed to init timer manager");
        goto error;
    }

    // 注册事件处理器
    event_loop_register_handler(manager->event_loop, EVENT_API_RESPONSE,
                                (event_handler_t)system_manager_handle_api_response);
    event_loop_register_handler(manager->event_loop, EVENT_DATA_UPDATE,
                                (event_handler_t)system_manager_handle_data_update);
    event_loop_register_handler(manager->event_loop, EVENT_TIMER_TRIGGER,
                                (event_handler_t)system_manager_handle_timer_trigger);
    event_loop_register_handler(manager->event_loop, EVENT_DATA_CHECK,
                                (event_handler_t)system_manager_handle_data_check);

    manager->initialized = true;
    return SUCCESS;

error:
    system_manager_cleanup(manager);
    return ERROR_INVALID_PARAM;
}

void system_manager_setup_api_tasks(system_manager_t *manager) {
    if (!manager || !manager->initialized) {
        return;
    }

    // 设置API调用定时任务
    json_t *apis = config_manager_get(manager->config, "apis");
    if (apis && json_is_object(apis)) {
        const char *api_name;
        json_t *api_config;
        json_object_foreach(apis, api_name, api_config) {
            json_t *interval = json_object_get(api_config, "interval_ms");
            if (interval && json_is_integer(interval)) {
                int interval_ms = json_integer_value(interval);
                char task_name[256];
                snprintf(task_name, sizeof(task_name), "api_%s", api_name);

                timer_manager_add_task(manager->timer, task_name, interval_ms,
                                       api_timer_callback, manager, false);
                LOG_INFO("Added API task: %s, interval: %dms", task_name, interval_ms);
            }
        }
    }
}

void system_manager_setup_monitor_tasks(system_manager_t *manager) {
    if (!manager || !manager->initialized) {
        return;
    }

    // 设置数据监控定时任务
    json_t *monitors = config_manager_get(manager->config, "monitors");
    if (monitors && json_is_object(monitors)) {
        const char *monitor_name;
        json_t *monitor_config;
        json_object_foreach(monitors, monitor_name, monitor_config) {
            json_t *interval = json_object_get(monitor_config, "check_interval_ms");
            if (interval && json_is_integer(interval)) {
                int interval_ms = json_integer_value(interval);
                char task_name[256];
                snprintf(task_name, sizeof(task_name), "monitor_%s", monitor_name);

                timer_manager_add_task(manager->timer, task_name, interval_ms,
                                       data_check_timer_callback, manager, false);
                LOG_INFO("Added monitor task: %s, interval: %dms", task_name, interval_ms);
            }
        }
    }
}

int system_manager_start(system_manager_t *manager) {
    if (!manager || !manager->initialized) {
        return ERROR_INVALID_PARAM;
    }

    // 启动事件循环
    if (event_loop_start(manager->event_loop) != SUCCESS) {
        return ERROR_THREAD_CREATE;
    }

    // 设置定时任务
    system_manager_setup_api_tasks(manager);
    system_manager_setup_monitor_tasks(manager);

    // 启动定时器管理器
    timer_manager_start(manager->timer);

    // 初始化API客户端
    api_client_init();

    manager->running = true;
    LOG_INFO("System manager started successfully");

    return SUCCESS;
}

void system_manager_stop(system_manager_t *manager) {
    if (!manager || !manager->running) {
        return;
    }

    manager->running = false;

    // 停止定时器
    if (manager->timer) {
        timer_manager_stop(manager->timer);
    }

    // 停止事件循环
    if (manager->event_loop) {
        event_loop_stop(manager->event_loop);
    }

    // 清理API客户端
    api_client_cleanup();

    LOG_INFO("System manager stopped");
}

void system_manager_cleanup(system_manager_t *manager) {
    if (!manager) {
        return;
    }

    system_manager_stop(manager);

    if (manager->timer) {
        timer_manager_destroy(manager->timer);
        free(manager->timer);
    }

    if (manager->data_pool) {
        data_pool_destroy(manager->data_pool);
        free(manager->data_pool);
    }

    if (manager->config) {
        config_manager_destroy(manager->config);
        free(manager->config);
    }

    if (manager->event_loop) {
        event_loop_cleanup(manager->event_loop);
        free(manager->event_loop);
    }
}
